<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>Expenditure all income</title>
    <style type="text/css">
        body {
            text-align: center;
            font: 10px sans-serif;
            margin: 0;
        }
        svg {
            font: 10px sans-serif;
        }
        .header {
            font: 15px sans-serif;
        }
        div.tooltip {
            position: absolute;
            text-align: left;
            padding: 8px;
            font: 10px sans-serif;
            background: #ddd;
            border: solid 1px #aaa;
            border-radius: 8px;
            pointer-events: none;
        }
        .node circle {
            fill: #fff;
            stroke: steelblue;
            stroke-width: 1.5px;
        }
        .node {
            font: 10px sans-serif;
        }
        .link {
            fill: none;
            stroke: #ccc;
            stroke-width: 1.5px;
        }
  
    </style>
    <script type="text/javascript" src="../js/d3.js"></script>
    <script type="text/javascript" src="../js/dimple.v2.1.0.js"></script>
    <script src="../js/pace/pace.js"></script>
    <link href="../js/pace/themes/loadingBar.css" rel="stylesheet" />
    <script type="text/javascript" src="ExpanditureAllIncomeA.js"></script>
    <script type="text/javascript" src="ExpanditureAllIncomeB.js"></script>
</head>

<body>
    <div id="sortMenu" style="width:100%;text-align:right;position: fixed;background-color: rgb(255,255,255);">
        รูปแบบกราฟ
        <input type="radio" name="radioGraphType" value="drillDown" id="radio" checked="checked" onchange="graphType(this)">drill down
        <input type="radio" name="radioGraphType" value="tree" id="radio" onchange="graphType(this)">tree
        <input type="radio" name="radioGraphType" value="sunburst" id="radio" onchange="graphType(this)">sunburst
    </div>
    
    <script type="text/javascript">
        var dataTreeGraph;
        
        function removeDiv(divName){
        	if(document.getElementById(divName)!=null){
        		document.getElementById(divName).remove();
        	}
        }
        
        function disableRadioBox(radioName){
        	var radioBox = document.getElementsByName(radioName);
			for (var i = 0; i < radioBox.length; i++) {
				radioBox[i].disabled = true;
			}
        }
        
        function enableRadioBox(radioName){
        	var radioBox = document.getElementsByName(radioName);
			for (var i = 0; i < radioBox.length; i++) {
				radioBox[i].disabled = false;
			}
        }
        
        function graphType(p) {
            if (p.value == "drillDown") {
                //delete tree graph
                removeDiv("treeGraph");
                removeDiv("header");
              	//delete tree sunbrust graph
                removeDiv("sunburstDiv");
              	//generate drill down graph
                drilldownGraph();
            } else if (p.value == "tree") {
                //delete drill down graph
                removeDiv("drilldownDiv");
                removeDiv("header");
                //delete sunburst graph
                removeDiv("sunburstDiv");
                
                //check data is never defined for load data
                if ((typeof dataTreeGraph) == "undefined") {
                    //disable radio box
                    disableRadioBox("radioGraphType");

                    d3.json("../XPD002Controller?graphType=tree", function(error, data) {
                        dataTreeGraph = JSON.parse(JSON.stringify(data));
                        collapsibleTree(data);
                        //enable radio box
                        enableRadioBox("radioGraphType");
                    }); //end d3.json
                } else {
                    //clone object for gen tree graph without load new data
                    var newObject = JSON.parse(JSON.stringify(dataTreeGraph));
                    collapsibleTree(newObject);
                }
            } else {
            	removeDiv("drilldownDiv");
            	removeDiv("treeGraph");
            	removeDiv("header");
            	sunburst();
            }
        }
        
        //Global variable
        var navi1,navi2,navi3,navi4;
        
        function navigator(divName,root){
        	var width = 600;
    		var height = 50;
    		
    		var cluster = d3.layout.cluster().size([height, width-160]);
    		
    		var diagonal = d3.svg.diagonal().projection(function(d) { return [d.y, d.x]; });
    	
    	
    		//d3.select("body").append("div").attr("id","navigateGraph");
    		var svg = d3.select("#"+divName).append("svg")
    			.attr("width", width)
    			.attr("height", height)
    			.append("g")
    			.attr("transform", "translate(60,0)");
    		var nodes = cluster.nodes(root);
    		var links = cluster.links(nodes);

    		var link = svg.selectAll(".link")
    			.data(links)
    			.enter().append("path")
    			.attr("class", "link")
    			.attr("d", diagonal);
    	
    		var node = svg.selectAll(".node")
    			.data(nodes)
    			.enter().append("g")
    			.attr("class", "node")
    			.attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; })
    		
    			node.append("circle")
    			.attr("r", 4.5);
    	
    		node.append("text")
    		.attr("dx",-20)
    		//.attr("dx", function(d) { return d.children ? -8 : 8; })
    		.attr("dy", -8)
    		.style("text-anchor", "start")
    		//.style("text-anchor", function(d) { return d.children ? "end" : "start"; })
    		.text(function(d) { return d.name; });
    		d3.select(self.frameElement).style("height", height + "px");
    		
    		//Global variable
    		var navi = d3.select("#"+divName).selectAll("g.node").selectAll("circle");
    		navi.forEach(function(d,i){
    			if(i==0){
    				navi1 = d[0];
    			}else if(i==1){
    				navi2 = d[0];
    			}else if(i==2){
    				navi3 = d[0];
    			}else{
    				navi4 = d[0];
    			}
    		});
        }

        // initail graph
        drilldownGraph();

        function drilldownGraph() {
	        	var header = d3.select("body").append("div").attr("id","header").attr("class","header").attr("style","position: fixed;top: 18px;width: 100%;background-color: rgb(255,255,255);");
				header.html("<a href='../index.html'><img src='../images/home_icon.png'></a> รายงานงบประมาณ มหาวิทยาลัยราชภัฏรำไพพรรณี <br/>");
				d3.select("#header").append("div").attr("id","navigator").attr("style","width: 100%; position: fixed; top: 59px;background-color: rgb(255,255,255);");
				var root = {"name":"ปี",
						"children":[{"name":"ประเภท",
							"children":[{"name":"หน่วยงาน",
								"children":[{"name":"โครงการ"}]
							}]
						}]
				};
				navigator("navigator",root);
				navi1.style.fill = "rgb(176,196,222)";
				navi2.style.fill = "rgb(255,255,255)";
				navi3.style.fill = "rgb(255,255,255)";
				navi4.style.fill = "rgb(255,255,255)";
        		
				d3.select("body").append("div").attr("id", "drilldownDiv");
        		
               	d3.select("#drilldownDiv").append("div").attr("id", "lineContainer");
                d3.json("../XPD002Controller?graphType=line", function(error, data) {
                    var svg = dimple.newSvg("#lineContainer", 1024, 500);
                    var myChart = new dimple.chart(svg, data);
                    myChart.setBounds(60, 120, 800, 300);
                    var x = myChart.addCategoryAxis("x", "name");
                    var y = myChart.addMeasureAxis("y", "amount");

                    x.title = "ปี";
                    y.title = "จำนวนเงิน";

                    var lines = myChart.addSeries(null, dimple.plot.line);
                    lines.lineWeight = 3;
                    lines.lineMarkers = true;
                    lines.addEventHandler("click", onClick);

                    lines.getTooltipText = function(e) {
                        return [
                            "ปี: " + e.x,
                            "จำนวนเงิน: " + e.y.toLocaleString("th-TH") + " บาท"
                        ];
                    };
                    myChart.draw(600);

                    function onClick(e) {
                        //remove old div before rander new div
                        //call method firstDrilldown. e.xValue is a value of period
                        firstDrilldown(e.xValue);
                    }
                }); //end d3.json
            } //end line graph

        function goToAnchor(name) {
            //var top = document.getElementById(name).offsetTop;
            //window.scrollTo(0, top);
            document.getElementById(name).scrollIntoView(true);
        }

        function firstDrilldown(period) {
        	removeDiv("donutContainer");
        	removeDiv("barContainer");
        	removeDiv("barContainer2");
            
        	navi2.style.fill = "rgb(176,196,222)";
			navi3.style.fill = "rgb(255,255,255)";
			navi4.style.fill = "rgb(255,255,255)";
			
            var header = d3.select("#drilldownDiv").append("div").attr("id", "donutContainer");
            header.append("p").attr("class", "header").text("รายงานงบประมาณ จำแนกตามประเภทงบประมาณ ปี " + period);
            d3.json("../XPD002Controller?graphType=line&period=" + period, function(error, data) {
                var m = 200,
                    r = 100,
                    z = d3.scale.category20();

                var position = Math.PI / 180;

                //linearScale
                var maxInitData = d3.max(data, function(d) {
                    return d.amount
                });
                var minInitData = d3.min(data, function(d) {
                    return d.amount
                });
                var logScale = d3.scale.log().domain([minInitData, maxInitData]).nice().range([0, 100]);

                var pie = d3.layout.pie()
                    .value(function(d) {
                        return logScale(d.amount);
                    })
                    .sort(null);

                var arc = d3.svg.arc()
                    .innerRadius(r / 2)
                    .outerRadius(r);

                var budget = d3.nest()
                    .key(function(d) {
                        return d.budgetPeriodId;
                    })
                    .entries(data);

                var svg = d3.select("#donutContainer").selectAll("div")
                    .data(budget)
                    .enter()
                    .append("div")
                    .attr("id", "donut")
                    .style("display", "inline")
                    .style("width", 1024 + "px")
                    .style("height", 768 + "px")
                    .append("svg:svg")
                    .attr("width", (r + m) * 2)
                    .attr("height", (r + m) * 2)
                    .append("svg:g")
                    .attr("transform", "translate(" + (r + m) + "," + (r + m) + ")");

                svg.append("svg:text")
                    .attr("dy", ".35em")
                    .attr("text-anchor", "middle")
                    .text(function(d) {
                        return d.key;
                    });

                var g = svg.selectAll("g")
                    .data(function(d) {
                        return pie(d.values);
                    })
                    .enter().append("svg:g");

                g.append("svg:path")
                    .attr("class", "arc")
                    .style("fill", function(d) {
                        return z(d.data.name);
                    })
                    //.on("click",function(d) {firstDrilldown(d.data.rewardId,d.data.rewardName);})
                    .on("mouseover", mouseover)
                    .on("mouseout", mouseout)
                    .on("click", onClick)
                    .transition()
                    .ease("exp")
                    .ease("bounce")
                    .duration(2500)
                    .delay(function(d, i) {
                        return i * 10;
                    })
                    .attrTween("d", tweenPie);

                function tweenPie(b) {
                    var i = d3.interpolate({
                        startAngle: -30 * position,
                        endAngle: -31 * position
                    }, b);
                    return function(t) {
                        return arc(i(t));
                    };
                }

                //append tooltip
                var tip = d3.select("body").append("div")
                    .attr("class", "tooltip")
                    .style("opacity", 1e-6);

                function mouseover(d) {
                    tip.transition().duration(500).style("opacity", 1);
                    tip.html("งบประมาณ: " + d.data.name + "<br/> จำนวนเงิน: " + d.data.amount.toLocaleString("th-TH"))
                        .style("left", (d3.event.pageX - 34) + "px")
                        .style("top", (d3.event.pageY - 12) + "px");
                }

                function mouseout() {
                    tip.transition().duration(500).style("opacity", 1e-6);
                }

                function onClick(d) {
                    secondDrilldown(d.data.budgetPeriodId, d.data.budgetGroupId, d.data.name);
                }

                var pos = d3.svg.arc().innerRadius(r - 30).outerRadius(r + 50);


                g.append("svg:text")
                    .attr("dy", ".35em")
                    .attr("text-anchor", positionLabel)
                    //.attr("transform", function(d) {return "translate(" + pos.centroid(d) + ")";})
                    .text(function(d) {
                        return d.data.name;
                    })
                    .transition()
                    .ease("exp")
                    .ease("bounce")
                    .duration(2500)
                    .delay(function(d, i) {
                        return i * 10;
                    })
                    .attrTween("transform", tweenText);

                function tweenText(b) {
                    var i = d3.interpolate({
                        startAngle: -30 * position,
                        endAngle: -31 * position
                    }, b);
                    return function(t) {
                        return "translate(" + pos.centroid(i(t)) + ")rotate(" + angle(i(t)) + ")";
                    };
                }

                var getAngle = function(d) {
                    return (180 / Math.PI * (d.startAngle + d.endAngle) / 2 - 90);
                };

                g.append("svg:text")
                    .attr("dy", ".35em")
                    .attr("text-anchor", "middle")
                    //.attr("transform", function(d) {return "translate(" + arc.centroid(d) + ")";})
                    .text(function(d) {
                        return (d.data.amount / 1000000).toFixed(2) + "m";
                    })
                    .transition()
                    .ease("exp")
                    .ease("bounce")
                    .duration(2500)
                    .delay(function(d, i) {
                        return i * 10;
                    })
                    .each(function(d) {
                        var bb = this.getBBox(),
                            center = arc.centroid(d);

                        var topLeft = {
                            x: center[0] + bb.x,
                            y: center[1] + bb.y
                        };

                        var topRight = {
                            x: topLeft.x + bb.width,
                            y: topLeft.y
                        };

                        var bottomLeft = {
                            x: topLeft.x,
                            y: topLeft.y + bb.height
                        };

                        var bottomRight = {
                            x: topLeft.x + bb.width,
                            y: topLeft.y + bb.height
                        };

                        d.visible = pointIsInArc(topLeft, d, arc) &&
                            pointIsInArc(topRight, d, arc) &&
                            pointIsInArc(bottomLeft, d, arc) &&
                            pointIsInArc(bottomRight, d, arc);
                    })
                    .style('display', function(d) {
                        return d.visible ? null : "none";
                    })

                .attrTween("transform", tweenAmount);

                function tweenAmount(b) {
                    var i = d3.interpolate({
                        startAngle: -30 * position,
                        endAngle: -31 * position
                    }, b);
                    return function(t) {
                        //return "translate(" + arc.centroid(i(t)) + ")rotate("+angle(i(t))+")";
                        return "translate(" + arc.centroid(i(t)) + ")";
                    };
                }

                function pointIsInArc(pt, ptData, d3Arc) {
                    // Center of the arc is assumed to be 0,0
                    // (pt.x, pt.y) are assumed to be relative to the center
                    var r1 = arc.innerRadius()(ptData),
                        r2 = arc.outerRadius()(ptData),
                        theta1 = arc.startAngle()(ptData),
                        theta2 = arc.endAngle()(ptData);

                    var dist = pt.x * pt.x + pt.y * pt.y,
                        angle = Math.atan2(pt.x, -pt.y);

                    angle = (angle < 0) ? (angle + Math.PI * 2) : angle;

                    return (r1 * r1 <= dist) && (dist <= r2 * r2) &&
                        (theta1 <= angle) && (angle <= theta2);
                }

                function angle(d) {
                    var a = (d.startAngle + d.endAngle) * 90 / Math.PI - 90;
                    return a > 90 ? a - 180 : a;
                }

                function positionLabel(d) {
                    var a = (d.startAngle + d.endAngle) * 90 / Math.PI - 90;
                    return a > 90 ? "end" : "start";
                }

                //d3.select("body").append("div").attr("id","markDonut");
                goToAnchor("donutContainer");
            }); //end d3.json
        } //end firstDrilldown

        function secondDrilldown(period, budgetId, budgetName) {
        	removeDiv("barContainer");
        	removeDiv("barContainer2");
        	
			navi3.style.fill = "rgb(176,196,222)";
			navi4.style.fill = "rgb(255,255,255)";
        	
	        var header = d3.select("#drilldownDiv").append("div").attr("id", "barContainer");
	        header.append("p").attr("class", "header").text("รายงานงบประมาณ " + budgetName + " จำแนกตามหน่วยงาน");
	        d3.json("../XPD002Controller?graphType=line&period=" + period + "&budgetId=" + budgetId, function(error, data) {
	            var maxInitData = d3.max(data, function(d) {
	                return d.amount
	            });
	            var minInitData = d3.min(data, function(d) {
	                return d.amount
	            });
	            var logScale = d3.scale.log().domain([minInitData, maxInitData]).nice().range([minInitData, maxInitData]);
	            var svg = dimple.newSvg("#barContainer", 800, 500);
	            var myChart = new dimple.chart(svg, data);
	            myChart.setBounds(300, 30, 490, 430)
	            var x = myChart.addLogAxis("x", "amount").hidden = true;
	            var y = myChart.addCategoryAxis("y", "name");
	            y.addOrderRule("amount");
	            x.title = "จำนวนเงิน";
	            y.title = "หน่วยงาน";
	            //y.addOrderRule("Date");
	            var mySeries = myChart.addSeries(null, dimple.plot.bar);
	
	            mySeries.addEventHandler("click", onClick);
	
	            //Customize tooltip
	            mySeries.getTooltipText = function(e) {
	                return [
	                    "หน่วยงาน: " + e.y,
	                    "จำนวนเงิน: " + e.xValue.toLocaleString("th-TH") + " บาท"
	                ];
	            };
	            myChart.draw(600);
	
	            function onClick(e) {
	                    //search department name for find department id 
	                    var depId;
	                    data.some(function(d, i) {
	                        if (d.name.localeCompare(e.yValue) == 0) {
	                            depId = d.depId;
	                        }
	                    });
	                    thirdDrilldown(period, budgetId, depId, e.yValue);
	                }
	                //d3.select("body").append("div").attr("id","markBar");
	            goToAnchor("barContainer");
	
	        }); //end d3.json
	    } //end second drill down 
	
	function thirdDrilldown(period, budgetId, depId, depName) {
	    	removeDiv("barContainer2");
	    	navi4.style.fill = "rgb(176,196,222)";
	    	
	        var header = d3.select("#drilldownDiv").append("div").attr("id", "barContainer2");
	        header.append("p").attr("class", "header").text("รายงานงบประมาณแยกตามโครงการ ของ " + depName);
	        d3.json("../XPD002Controller?graphType=line&period=" + period + "&budgetId=" + budgetId + "&depId=" + depId, function(error, data) {
	            var svg = dimple.newSvg("#barContainer2", 800, 500);
	            var myChart = new dimple.chart(svg, data);
	            myChart.setBounds(300, 30, 490, 430)
	            var x = myChart.addMeasureAxis("x", "amount");
	            var y = myChart.addCategoryAxis("y", "name");
	            y.addOrderRule("amount");
	            x.title = "จำนวนเงิน";
	            y.title = "โครงการ";
	            var mySeries = myChart.addSeries(null, dimple.plot.bar);
	
	            mySeries.getTooltipText = function(e) {
	                return [
	                    "โครงการ: " + e.y,
	                    "จำนวนเงิน: " + e.xValue.toLocaleString("th-TH") + " บาท"
	                ];
	            };
	            myChart.draw(600);
	
	            goToAnchor("barContainer2");
	        }); //end d3.json
	    } //end third drill down
    </script>
</body>

</html>
